﻿
$(function () {
    Show()
})
//车间列表
function Show() {
    layui.use(function () {
        var table = layui.table;
        var layer = layui.layer;
        var $ = layui.jquery;
        //var workshopNo = $("#workshopNo").val();
        //var workshopName = $("#workshopName").val();
        //var workshopState = $("#workshopState").val();

        var workNo = $("#workNo").val();
        var workName = $("#workName").val();
        var State = $("#State").val();
        console.log(table)
        // 点击批量删除按钮的事件处理
        $('#batch-delete-btn').click(function () {
            var checkStatus = table.checkStatus('carriertable');
            var workshopId = checkStatus.data.map(function (item) { return item.workshopId; });
            console.log(workshopId)
            if (workshopId.length === 0) {
                layer.msg('请至少选择一条要删除的数据', { icon: 2 });
                return;
            }
            layer.confirm('确定要批量删除选中的 ' + workshopId.length + ' 条数据吗？', function (index) {
                console.log(workshopId)
                localStorage.setItem("Token", "")

                // 发送Ajax请求到后端，传递选中的id数组进行删除操作
                $.ajax({
                    url: '/Workshops/WorkshopsPiDelete', // 后端批量删除接口地址，根据实际调整
                    type: 'Post',
                    data: {
                        Data: JSON.stringify(workshopId),
                        Token: localStorage.getItem("Token")
                    },
                    success: function (res) {
                        var res = JSON.parse(res)
                        console.log(res)
                        if (res.data > 0) {
                            layer.msg('批量删除成功', { icon: 1 });
                            Show()
                        } else {
                            layer.msg('批量删除失败：' + res.message, { icon: 2 });
                        }
                        layer.close(index);
                    },
                    error: function () {
                        layer.msg('请求出错，请稍后再试', { icon: 2 });
                        layer.close(index);
                    }
                });
            });
        });

        // 先进行表格的初始渲染
        table.render({
            elem: '#carriertable',  // 表格元素的选择器
            page: {
                limit: 5,
                limits: [3, 5, 8, 10]
            },
            toolbar: '#toolbarDemo',
            defaultToolbar: ['exports'],
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'workshopId', title: '车间id' },
               { field: 'workshopNo', title: '车间编号' },
               { field: 'workshopName', title: '车间名称' },
                {
                    field: 'workshopLocation', title: '车间位置', templet: function (d) {
                        var locations = ['', '位置一', '位置二', '位置三'];
                        return locations[d.workshopLocation];
                    }
                },
               { field: 'workshopLeader', title: '车间负责人' },
               {field: 'workshopContact', title: '联系方式'},
                {field: 'workshopState', title: '状态',templet: function (d) {
                        return d.workshopState == 1 ? '正常' : '异常';
                    }
                },
               {
                   field: '', title: '操作', templet: function (d) {
                       return '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="editData(' + d.workshopId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' + '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="editFind(' + d.workshopId + ')"><i class="layui-icon layui-icon-edit"></i>查看</a> ' +
                           '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.workshopId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>' + '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="stateData(' + d.workshopId + ')">' +
                           '<i class="layui-icon layui-icon-delete"></i>' +
                           (d.workshopState == '1' ? '停工' : '恢复') + '</a>';
                    }
                }
            ]],
            
            // 初始时可以先不加载数据，等待 ajax 请求成功后再更新
            data: []
        });
        // 创建表格实例
        $.ajax({
            url: "/Workshops/WorkshopsShow",
            type: "get",
            data: {
                pageIndex: 1,
                pageSize: 100,
                workshopNo: workNo,
                workshopName: workName,
                workshopState: State || 0,
            },
            success: function (data) {
                data = JSON.parse(data);
                console.log(data.data.pageList);
                // 在 ajax 请求成功后，使用正确的表格 ID 进行 reload
                table.reload('carriertable', {
                    page: {
                        limit: 5,
                        limits: [3, 5, 8, 10]
                    },
                    data: data.data.pageList
                });
            },
            error: function () {
                console.log("请求失败");
            }
        });
    });
}


//查看跳转按钮
window.editFind = function (workshopId) {
    localStorage["workshopId"] = workshopId
    location.href = "/Workshops/WorkshopsFind";
}



//修改设备状态
window.stateData = function (workshopId) {
    // 先根据id获取要编辑的数据，发起Ajax请求
    console.log(workshopId)
    var form = layui.form;
    $.ajax({
        type: "get",
        url: "/Workshops/WorkshopsState",  // 替换为实际的后台根据id获取数据的接口地址
        data: { workshopId: workshopId, token: localStorage.getItem("token") },
        success: function (res) {
            var res = JSON.parse(res)
            if (res.data >= 1) {
                layer.alert("修改状态成功");
                Show();  // 重新加载数据，刷新表格显示
            } else {
                layer.alert("修改状态失败");

            }
        },
    });
}

//删除
window.deleteData = function (workshopId) {
    console.log(workshopId);
    layer.confirm('确定要删除该条数据吗？', function (index) {
        $.ajax({
            type: "Post",
            url: "/Workshops/WorkshopsDelete",  // 替换为实际的后台删除数据接口地址
            data: { data: JSON.stringify({ workshopId: workshopId }), token: localStorage.getItem("token") },
            success: function (res) {
                var res = JSON.parse(res)
                if (res.data >= 1) {
                    layer.alert("删除成功");
                    Show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("删除失败");

                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};

//车间添加
layui.use('layer', function () {
    var $ = layui.$;
    var layer = layui.layer;
    var util = layui.util;
    var form = layui.form;
    var table = layui.table;

    // 打开添加弹窗的按钮点击事件
    util.on('lay-on', {
        'test-page-custom': function () {
            layer.open({
                type: 1,
                title: "新增车间信息",
                content: `<form class="layui-form" style="padding:80px;">
                    <div class="layui-form-item">
                    <label class="layui-form-label">车间编号：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="workshopNo" id="workshopNo" autocomplete="off" placeholder="请输入车间编号" class="layui-input">
                    </div>
                    </div>
                     <div class="layui-form-item">
                    <label class="layui-form-label">车间名称：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="workshopName" id="workshopName" autocomplete="off" placeholder="请输入车间名称" class="layui-input">
                    </div>
                    </div>
                    <div class="layui-form-item">
                   <label class="layui-form-label">车间位置：</label>
                   <div class="layui-input-inline">
                       <select name="workshopLocation" id="workshopLocation" required lay-verify="required">
                           <option value="">请选择</option>
                           <option value="1">位置一</option>
                           <option value="2">位置二</option>
                           <option value="3">位置三</option>
                       </select>
                   </div>
                    </div>
                    <div class="layui-form-item">
                    <label class="layui-form-label">车间负责人：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="workshopLeader" id="workshopLeader" autocomplete="off" placeholder="请输入车间负责人" class="layui-input">
                    </div>
                    </div>
                    <div class="layui-form-item">
                    <label class="layui-form-label">联系方式：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="workshopContact" id="workshopContact" autocomplete="off" placeholder="请输入车间联系方式" class="layui-input">
                    </div>
                    </div>
                     <div class="layui-form-item">
                   <label class="layui-form-label">状态: </label>
                   <div class="layui-input-inline">
                       <input type="radio" name="workshopState"  value="1" checked>正常
                       <input type="radio" name="workshopState"  value="2">异常
                   </div>
                   </div>
                    <div class="layui-input-block">
                    <button class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                     <button class="layui-btn" lay-submit lay-filter="demo-login">添加</button>
                    </div>
                    <form>`,
                success: function () {

                    // 对弹层中的表单进行初始化渲染
                    form.render();
                    // 表单提交事件
                    form.on('submit(demo-login)', function (data) {
                        var field = data.field;
                        console.log(field)
                        $.ajax({
                            url: '/Workshops/WorkshopsAdd',
                            type: 'post',
                            data: { data: JSON.stringify(field), token: localStorage.getItem("token") },
                            success: function (res) {
                                var s = JSON.parse(res)
                                console.log(res)
                                if (s.code == 1) {
                                    layer.alert("添加成功");
                                    setTimeout(function () {
                                        location.reload();
                                    }, 2000);
                                }
                                else {
                                    layer.alert("添加失败");
                                }
                            }
                        })
                        return false; // 阻止默认 form 跳转
                    });
                }
            });

        }
    })
});


var obj = {
    workshopId: '',
    workshopNo: '',
    workshopName: '',
    workshopLocation: '',
    workshopLeader: '',
    workshopContact: '',
    workshopState:'',
    addName: '',
    addTime: ''
}

window.editData = function (workshopId) {

    // 先根据id获取要编辑的数据，发起Ajax请求
    var form = layui.form;
    $.ajax({
        type: "get",
        url: "/Workshops/WorkshopsFinds",  // 替换为实际的后台根据id获取数据的接口地址
        data: { workshopId: workshopId, token: localStorage.getItem("token") },
        success: function (res) {
            var res = JSON.parse(res)
            console.log(res)
            $(res.data).each(function () {
                $('#workshopId').val(this.workshopId)
                $('#workshopNo').val(this.workshopNo)
                $('#workshopName').val(this.workshopName)
                $('#workshopLocation').val(this.workshopLocation)
                //反填下拉框要渲染
                form.render('select');
                $('#workshopLeader').val(this.workshopLeader)
                $('#workshopContact').val(this.workshopContact)
                // 反填单选框
                var workshopState = this.workshopState;
                $('input[name="workshopState"][value="' + workshopState + '"]').prop('checked', true);
                $('#addName').val(this.addName)
                $('#addTime').val(this.addTime)
                obj.workshopId = this.workshopId
                obj.workshopNo = this.workshopNo
                obj.workshopName = this.workshopName
                obj.workshopLocation = this.workshopLocation
                obj.workshopLeader = this.workshopLeader
                obj.workshopContact = this.workshopContact
                obj.workshopState = this.workshopState
                obj.addName = this.addName
                obj.addTime = this.addTime

            })
        },
    });

    layer.open({
        type: 1,
        title: '编辑车间信息',
        content: `<form class="layui-form" style="padding:30px;">
                    <div class="layui-form-item">
                    <label class="layui-form-label">车间编号：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="workshopNo" id="workshopNo" autocomplete="off" placeholder="请输入车间编号" class="layui-input">
                    </div>
                    </div>
                     <div class="layui-form-item">
                    <label class="layui-form-label">车间名称：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="workshopName" id="workshopName" autocomplete="off" placeholder="请输入车间名称" class="layui-input">
                    </div>
                    </div>
                    <div class="layui-form-item">
                   <label class="layui-form-label">车间位置：</label>
                   <div class="layui-input-inline">
                       <select name="workshopLocation" id="workshopLocation" required lay-verify="required">
                           <option value="1">请选择</option>
                           <option value="1">位置一</option>
                           <option value="2">位置二</option>
                           <option value="3">位置三</option>
                       </select>
                   </div>
                    </div>
                    <div class="layui-form-item">
                    <label class="layui-form-label">车间负责人：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="workshopLeader" id="workshopLeader" autocomplete="off" placeholder="请输入车间负责人" class="layui-input">
                    </div>
                    </div>
                    <div class="layui-form-item">
                    <label class="layui-form-label">联系方式：</label>
                    <div class="layui-input-inline">
                    <input type="text" name="workshopContact" id="workshopContact" autocomplete="off" placeholder="请输入车间联系方式" class="layui-input">
                    </div>
                    </div>
                     <div class="layui-form-item">
                   <label class="layui-form-label">状态: </label>
                   <div class="layui-input-inline">
                       <input type="radio" name="workshopState"  value="1" checked>正常
                       <input type="radio" name="workshopState"  value="2">异常
                   </div>
                   </div>
                    <div class="layui-input-block">
                    <button class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                     <button class="layui-btn" lay-submit lay-filter="demo-login">修改</button>
                    </div>
                    <form>
                    `,
        area: ['700px', '400px'],
        success: function () {
            var obj1 = {
                workshopId: '',
                workshopNo: '',
                workshopName: '',
                workshopLocation: '',
                workshopLeader: '',
                workshopContact: '',
                workshopState: '',
                addName: '',
                addTime: ''
            };
            console.log(obj1)
            // 对弹层中的表单进行初始化渲染
            form.render();
            // 表单提交事件
            form.on('submit(demo-login)', function (data) {
                var field = data.field;
                obj1.workshopId = obj.workshopId
                obj1.workshopNo = obj.workshopNo
                obj1.workshopName = obj.workshopName
                obj1.workshopLocation = field.workshopLocation
                obj1.workshopLeader = field.workshopLeader
                obj1.workshopContact = field.workshopContact
                obj1.workshopState = field.workshopState
                obj1.addName = obj.addName
                obj1.addTime = obj.addTime
                $.ajax({
                    url: '/Workshops/WorkshopsUpdate',
                    type: 'post',
                    data: { obj1, token: localStorage.getItem("token") },
                    success: function (res) {
                        var res = JSON.parse(res)
                        console.log(field)
                        console.log(res)
                        if (res.data >= 1) {
                            layer.alert("修改成功");
                            setTimeout(function () {
                                location.reload();
                            }, 2000);
                        }
                        else {
                            layer.alert("修改失败");
                        }
                    }
                })
                return false; // 阻止默认 form 跳转
            });
        }
    });
};

// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        var hour = ('0' + date.getHours()).slice(-2);
        var minute = ('0' + date.getMinutes()).slice(-2);
        var second = ('0' + date.getSeconds()).slice(-2);
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}





